#include <unistd.h>
#include <cstring>
#include "connection.hpp"
#include  "reactor.hpp"
#include "common.hpp"
#include "Slaver.hpp"
/*用于进程间通信的链接模块*/
const bool ReadEnd=false;
const bool WriteEnd=true;

class pipeconnection:public connection{
public:
    pipeconnection(bool PipeEnd,int pipefd):_PipeEnd(PipeEnd)
    {
        setfd(pipefd);
    }

    void setcommand(int command){_command=command;}

    virtual void _recv(){//读取主进程的数据
        if(_PipeEnd==WriteEnd) return;
        int n=::read(_sockfd,&_command,sizeof(int));
        if(n>0){
            if(_command==ACCEPT){
                //读取listensocket
                _own->accept();
            }
            else if(_command==EXIT){
                exit(0);
            }
            else{
            }
        }
        else if(n==0){//父进程关闭管道或者退出
            LOG(INFO)<<"child exit";
            exit(PARENTS_EXIT);
        }

    }
    virtual void _send(){//向子进程发送数据
        if(_PipeEnd==ReadEnd) return;
        ::write(_sockfd,&_command,sizeof(_command));
    }
    virtual void _except(){//对于链接IO的异常处理
        LOG(ERROR)<<"Pipe Error"<<strerror(errno);
        ::exit(PIPE_ERROR);
    }
private:
    bool _PipeEnd;
    int _command;
};

connect_t make_pipe(bool PipeEnd,int pipefd){
    return std::make_shared<pipeconnection>(PipeEnd,pipefd);
}